package com.mindskip.xzs.controller.student;

import com.github.pagehelper.PageInfo;
import com.mindskip.xzs.base.BaseApiController;
import com.mindskip.xzs.base.RestResponse;
import com.mindskip.xzs.domain.ExamPaperQuestionCustomerAnswer;
import com.mindskip.xzs.domain.Subject;
import com.mindskip.xzs.domain.TextContent;
import com.mindskip.xzs.domain.question.QuestionObject;
import com.mindskip.xzs.service.ExamPaperQuestionCustomerAnswerService;
import com.mindskip.xzs.service.QuestionService;
import com.mindskip.xzs.service.SubjectService;
import com.mindskip.xzs.service.TextContentService;
import com.mindskip.xzs.utility.DateTimeUtil;
import com.mindskip.xzs.utility.HtmlUtil;
import com.mindskip.xzs.utility.JsonUtil;
import com.mindskip.xzs.utility.PageInfoHelper;
import com.mindskip.xzs.viewmodel.admin.question.QuestionEditRequestVM;
import com.mindskip.xzs.viewmodel.student.exam.ExamPaperSubmitItemVM;
import com.mindskip.xzs.viewmodel.student.question.answer.QuestionAnswerVM;
import com.mindskip.xzs.viewmodel.student.question.answer.QuestionPageStudentRequestVM;
import com.mindskip.xzs.viewmodel.student.question.answer.QuestionPageStudentResponseVM;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController("StudentQuestionAnswerController")
@RequestMapping(value = "/api/student/question/answer")
@Slf4j
public class QuestionAnswerController extends BaseApiController {

    private final ExamPaperQuestionCustomerAnswerService examPaperQuestionCustomerAnswerService;
    private final QuestionService questionService;
    private final TextContentService textContentService;
    private final SubjectService subjectService;

    @Autowired
    public QuestionAnswerController(ExamPaperQuestionCustomerAnswerService examPaperQuestionCustomerAnswerService,
            QuestionService questionService, TextContentService textContentService, SubjectService subjectService) {
        this.examPaperQuestionCustomerAnswerService = examPaperQuestionCustomerAnswerService;
        this.questionService = questionService;
        this.textContentService = textContentService;
        this.subjectService = subjectService;
    }

    @RequestMapping(value = "/page", method = RequestMethod.POST)
    public RestResponse<PageInfo<QuestionPageStudentResponseVM>> pageList(
            @RequestBody QuestionPageStudentRequestVM model) {
        model.setCreateUser(getCurrentUser().getId());
        PageInfo<ExamPaperQuestionCustomerAnswer> pageInfo = examPaperQuestionCustomerAnswerService.studentPage(model);
        PageInfo<QuestionPageStudentResponseVM> page = PageInfoHelper.copyMap(pageInfo, q -> {
            Subject subject = subjectService.selectById(q.getSubjectId());
            QuestionPageStudentResponseVM vm = modelMapper.map(q, QuestionPageStudentResponseVM.class);
            vm.setCreateTime(DateTimeUtil.dateFormat(q.getCreateTime()));
            TextContent textContent = textContentService.selectById(q.getQuestionTextContentId());
            QuestionObject questionObject = JsonUtil.toJsonObject(textContent.getContent(), QuestionObject.class);
            String clearHtml = HtmlUtil.clear(questionObject.getTitleContent());
            vm.setShortTitle(clearHtml);
            vm.setSubjectName(subject.getName());
            return vm;
        });
        return RestResponse.ok(page);
    }

    @RequestMapping(value = "/select/{id}", method = RequestMethod.POST)
    public RestResponse<QuestionAnswerVM> select(@PathVariable Integer id) {
        QuestionAnswerVM vm = new QuestionAnswerVM();
        ExamPaperQuestionCustomerAnswer examPaperQuestionCustomerAnswer = examPaperQuestionCustomerAnswerService
                .selectById(id);
        ExamPaperSubmitItemVM questionAnswerVM = examPaperQuestionCustomerAnswerService
                .examPaperQuestionCustomerAnswerToVM(examPaperQuestionCustomerAnswer);
        QuestionEditRequestVM questionVM = questionService
                .getQuestionEditRequestVM(examPaperQuestionCustomerAnswer.getQuestionId());
        vm.setQuestionVM(questionVM);
        vm.setQuestionAnswerVM(questionAnswerVM);
        return RestResponse.ok(vm);
    }

    private String buildAIPrompt(QuestionEditRequestVM question) {
        return String.format(
                "题目：%s\n选项：%s\n请以JSON格式返回分析结果，包含以下字段：\n" +
                        "- analysis（各选项详细解析）\n" +
                        "- correct（正确选项）\n" +
                        "- reasoning（解题思路）\n" +
                        "注意简答题填空题correct不用带上选项 严格按这个json格式响应 不要加任何其他多余标点 示例：" +
                        "{\n" +
                        "  \"analysis\": \"...分析\",\n"
                        +
                        "  \"correct\": \"...\",\n" +
                        "  \"reasoning\": \"...解题思路\"\n"
                        +
                        "}\n",
                question.getTitle(),
                String.join(",", question.getItems().stream()
                        .map(i -> i.getPrefix() + ":" + i.getContent())
                        .collect(Collectors.toList())));
    }

    @PostMapping("/aiAnalysis/{id}")
    public RestResponse<QuestionAnswerAIAnalysisDTO> aiAnalysis(@PathVariable Integer id) {
        ExamPaperQuestionCustomerAnswer answer = examPaperQuestionCustomerAnswerService.selectById(id);
        QuestionEditRequestVM questionVM = questionService.getQuestionEditRequestVM(answer.getQuestionId());

        List<Map<String, String>> messages = new ArrayList<>();
        Map<String, String> systemMsg = new HashMap<>();
        systemMsg.put("role", "system");
        systemMsg.put("content", "你是一个智能学习辅助机器人，请根据我的错题信息，提供详细的解析和解题思路。");
        messages.add(systemMsg);
        String prompt = buildAIPrompt(questionVM);
        Map<String, String> userMsg = new HashMap<>();
        userMsg.put("role", "user");
        userMsg.put("content", prompt);
        messages.add(userMsg);
        // 定义请求URL
        String url = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions";
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + "sk-78bc57a7c914408abcd14ef11ca92a79");
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "qwen-plus");
        requestBody.put("messages", messages);
        log.info("prompt:", prompt);
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
        try {
            ResponseEntity<Map> response = new RestTemplate().postForEntity(
                    url, requestEntity,
                    Map.class);
            log.info("AI解析结果:", response);
            if (response.getStatusCode() == HttpStatus.OK) {
                Map<String, Object> result = response.getBody();
                if (result != null && result.containsKey("choices")) {
                    List<Map<String, Object>> choices = (List<Map<String, Object>>) result.get("choices");
                    if (!choices.isEmpty()) {
                        Map<String, Object> message = (Map<String, Object>) choices.get(0).get("message");
                        String content = (String) message.get("content");

                        // 解析JSON响应
                        // 修改返回类型为DTO
                        Map<String, String> analysisResult = JsonUtil.toJsonObject(content, HashMap.class);
                        QuestionAnswerAIAnalysisDTO dto = new QuestionAnswerAIAnalysisDTO();
                        dto.setAnalysis(analysisResult.get("analysis"));
                        dto.setCorrect(analysisResult.get("correct"));
                        dto.setReasoning(analysisResult.get("reasoning"));
                        return RestResponse.ok(dto);
                    }
                }
            }
            return RestResponse.fail(500, "AI解析失败");
        } catch (Exception e) {
            log.error("AI解析异常", e);
            return RestResponse.fail(500, "服务暂时不可用");
        }
    }

    // 添加DTO类
    @Data
    public static class QuestionAnswerAIAnalysisDTO {
        private String analysis;
        private String correct;
        private String reasoning;
    }

    public static void main(String[] args) {
        // 定义请求URL
        String url = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions";
        // 创建 RestTemplate 实例
        RestTemplate restTemplate = new RestTemplate();
        List<Map<String, String>> messages = new ArrayList<>();
        Map<String, String> userMsg = new HashMap<>();
        userMsg.put("role", "user");
        userMsg.put("content", "你是？ 1+1=?");
        messages.add(userMsg);

        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + "sk-78bc57a7c914408abcd14ef11ca92a79");
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "qwen-plus");
        requestBody.put("messages", messages);

        // 发送 POST 请求
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestEntity, String.class);

        // 输出响应结果
        if (responseEntity.getStatusCode() == HttpStatus.OK) {
            System.out.println("Response: " + responseEntity.getBody());
        } else {
            System.out.println("Error: " + responseEntity.getStatusCodeValue() + " - " + responseEntity.getBody());
        }
    }
}
